package pe.edu.upla.lamerced.desk.view.hospedaje;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import net.sf.jasperreports.view.JasperViewer;
import pe.edu.upla.lamerced.Inicial;
import pe.edu.upla.lamerced.Utiles;
import pe.edu.upla.lamerced.bean.Detallefactura;
import pe.edu.upla.lamerced.bean.Detservicios;
import pe.edu.upla.lamerced.bean.Factura;
import pe.edu.upla.lamerced.bean.Hospedaje;
import pe.edu.upla.lamerced.service.HospedajeService;
import pe.edu.upla.lamerced.service.ServiciosService;

public class FacturaNueva extends javax.swing.JInternalFrame {

   private ServiciosService serviciosService;
   private HospedajeService hospedajeService;
   private JDesktopPane escritorio;
   private Hospedaje hospedaje;
   private List<Detallefactura> listaDetalleFactura;
   private Factura factura;

   public JDesktopPane getEscritorio() {
      return escritorio;
   }
   public void setEscritorio(JDesktopPane escritorio) {
      this.escritorio = escritorio;
   }
   public Hospedaje getHospedaje() {
      return hospedaje;
   }
   public void setHospedaje(Hospedaje hospedaje) {
      this.hospedaje = hospedaje;
   }
    /** Creates new form FacturaNueva */
    public FacturaNueva() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblHabitacion = new javax.swing.JLabel();
        lblCliente = new javax.swing.JLabel();
        lblFecHospedaje = new javax.swing.JLabel();
        lblDias = new javax.swing.JLabel();
        lblPrecio = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblServicios = new javax.swing.JTable();
        btnPrevioFactura = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lblbruto = new javax.swing.JLabel();
        lbligv = new javax.swing.JLabel();
        lblneto = new javax.swing.JLabel();
        btnFinalizaHospedaje = new javax.swing.JButton();

        setClosable(true);
        setTitle("Generar Factura");

        jLabel1.setText("Habitacion");

        jLabel2.setText("Cliente");

        jLabel3.setText("Inicio de Hospedaje");

        jLabel4.setText("Dias");

        jLabel5.setText("Precio");

        lblHabitacion.setText("xxxxxxxxxxxxxxxx xxxxxxxxxxxx");

        lblCliente.setText("jLabel7");

        lblFecHospedaje.setText("jLabel8");

        lblDias.setText("jLabel9");

        lblPrecio.setText("jLabel10");

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel11.setText("Generar Factura");

        tblServicios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nombre", "Tarifa", "Cantidad", "A Pagar"
            }
        ));
        jScrollPane1.setViewportView(tblServicios);

        btnPrevioFactura.setText("Previsualizar Factura");
        btnPrevioFactura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevioFacturaActionPerformed(evt);
            }
        });

        jLabel6.setText("Monto Bruto");

        jLabel7.setText("I.G.V.");

        jLabel8.setText("Neto a Pagar");

        lblbruto.setText("jLabel9");

        lbligv.setText("jLabel10");

        lblneto.setText("jLabel12");

        btnFinalizaHospedaje.setText("Finalizar hospedaje");
        btnFinalizaHospedaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinalizaHospedajeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(121, 121, 121)
                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblHabitacion, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFecHospedaje, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                            .addComponent(lblDias, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                            .addComponent(lblPrecio, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(272, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel8)
                                .addComponent(jLabel7)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbligv)
                            .addComponent(lblbruto)
                            .addComponent(lblneto))
                        .addGap(9, 9, 9))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnPrevioFactura)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnFinalizaHospedaje)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblHabitacion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblCliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblFecHospedaje)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDias)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblPrecio))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblbruto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbligv)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblneto))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel8)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFinalizaHospedaje)
                    .addComponent(btnPrevioFactura))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnPrevioFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevioFacturaActionPerformed
       verFactura();
    }//GEN-LAST:event_btnPrevioFacturaActionPerformed

    private void btnFinalizaHospedajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizaHospedajeActionPerformed
       try {
          factura.getHospedaje().setEstado(3);
          factura.getHospedaje().getHabitacion().setEstado(0);
          hospedajeService.registrarFactura(factura,listaDetalleFactura);
          JOptionPane.showMessageDialog(this, "El hospedaje se ha finalizado y la factura se ha grabado");
          verFactura();
        } catch (Exception e) {
            e.printStackTrace();
		}
    }//GEN-LAST:event_btnFinalizaHospedajeActionPerformed

   public void verFactura(){
      try{
         File carpeta = new File("resources");
         String ruta = carpeta.getAbsolutePath();
         File f = new File(ruta+"/factura.jasper");

         Map parameters = new HashMap();

         parameters.put("montobruto", factura.getMontoBruto().toString());
         parameters.put("montoneto", factura.getMontoNeto().toString());
         parameters.put("igv", factura.getIgv().toString());
         parameters.put("nombrecliente", factura.getHospedaje().getUsersByIdUsuarioCli().getNombrecompleto());
         parameters.put("fecha",Utiles.dateToString( factura.getHospedaje().getFecAlquiler(), Utiles.FORMATO_FECHA_CORTA));
         parameters.put("habitacion", factura.getHospedaje().getHabitacion().getNumero().toString());
         parameters.put("dias", factura.getHospedaje().getDiasreserva().toString());

         //le paso la ruta de donde se encuentra mi reporte y co esto cmpila bien la ruta y
         //ubica  alas imagenes del reprote
         parameters.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(carpeta));
         //Preparacion del reporte (en esta etapa llena el diseño de reporte)
         JRBeanCollectionDataSource dataSource;
         dataSource = new JRBeanCollectionDataSource(listaDetalleFactura);
         JasperPrint jasperPrint = JasperFillManager.fillReport( new FileInputStream(f) ,parameters,dataSource);
         //Se lanza el Viewer de Jasper, no termina aplicación al salir
         JasperViewer jviewer = new JasperViewer(jasperPrint,false);
         jviewer.show();
       }
       catch (Exception j){
           j.printStackTrace();
       }
   }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFinalizaHospedaje;
    private javax.swing.JButton btnPrevioFactura;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCliente;
    private javax.swing.JLabel lblDias;
    private javax.swing.JLabel lblFecHospedaje;
    private javax.swing.JLabel lblHabitacion;
    private javax.swing.JLabel lblPrecio;
    private javax.swing.JLabel lblbruto;
    private javax.swing.JLabel lbligv;
    private javax.swing.JLabel lblneto;
    private javax.swing.JTable tblServicios;
    // End of variables declaration//GEN-END:variables

   public void preLoadForm(){
      if(serviciosService==null){
         serviciosService=(ServiciosService)Inicial.getFactory().getBean("serviciosService");
      }
      if(hospedajeService==null){
         hospedajeService = (HospedajeService)Inicial.getFactory().getBean("hospedajeService");
      }
       try {
      
           	getHospedaje().setEstado(3);
           	getHospedaje().getHabitacion().setEstado(0);
           	getHospedaje().setFecSalida(new Date());

           	Calendar cal = new GregorianCalendar();
           	cal.setTime(getHospedaje().getFecAlquiler());

           	Calendar cal2 = new GregorianCalendar();
           	cal2.setTime(getHospedaje().getFecSalida());
           	int dias = cal.get(Calendar.DAY_OF_YEAR);
           	int dias2 = cal2.get(Calendar.DAY_OF_YEAR);

           	getHospedaje().setDiasreserva(dias2 - dias);

           	List<Detservicios> lis = serviciosService.listarServicioHospedaje(getHospedaje().getIdhospedaje());

           	factura = new Factura();
           	factura.setHospedaje(getHospedaje());
                lblHabitacion.setText(""+getHospedaje().getHabitacion().getNumero());
                lblCliente.setText(""+getHospedaje().getUsersByIdUsuarioCli().getNombrecompleto());
                lblFecHospedaje.setText(""+getHospedaje().getFecAlquiler());
                lblDias.setText(""+ (dias2 - dias) );
                lblPrecio.setText("" + getHospedaje().getHabitacion().getPrecioBase());

           	factura.setFecha(new Date());
           	listaDetalleFactura = new ArrayList<Detallefactura>();
           	BigDecimal monto = getHospedaje().getHabitacion().getPrecioBase();
           	for(Detservicios det : lis){
           		listaDetalleFactura.add(new Detallefactura(factura,det, new Long( det.getServicios().getTarifa() *  det.getCantidad() )));
           		monto = monto.add ( new BigDecimal(det.getServicios().getTarifa()).multiply( new BigDecimal( det.getCantidad()) ));
           	}
           	factura.setMontoBruto(monto);
           	factura.setIgv( monto.multiply( new BigDecimal(0.19))   );
           	factura.setMontoNeto( monto.add( factura.getIgv() )  );
            pintagrilla();

            DecimalFormat df = new DecimalFormat("######.##");
            lblbruto.setText(""+ df.format( monto ) );
            lbligv.setText  (""+ df.format( monto.multiply(  new BigDecimal(0.19) )  ) );
            lblneto.setText (""+ df.format( monto.add( factura.getIgv() )  ));
            
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, e.getMessage());
	}
   }

   public void pintagrilla(){
        DefaultTableModel tabla = (DefaultTableModel) tblServicios.getModel();
        tabla.setRowCount(0);
        for (Detallefactura dfac : listaDetalleFactura) {
            Object[] fila = new Object[4];
            fila[0] = dfac.getDetservicios().getServicios().getNombre();
            fila[1] = dfac.getDetservicios().getServicios().getTarifa();
            fila[2] = dfac.getDetservicios().getCantidad();
            fila[3] = dfac.getMonto();
            tabla.addRow(fila);
        }
    }

}
